package tinycloud;


import tinycloud.net.Client;
import tinycloud.gui.frame.MainFrame;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author nicolas
 */
public class Daemon extends Thread {

    private MainFrame mainFrame;
    public Daemon(MainFrame mainFrame) {
        super();
        this.mainFrame = mainFrame;
        start();
    }

    public void run() {
        while(true) {
            if(check()) {
                LinkedList<String> l;
                l = getList();
                String server = null;
                String port = null;
                Connection c;
                try {
                    Class.forName("org.hsqldb.jdbcDriver").newInstance();
                    c = DriverManager.getConnection("jdbc:hsqldb:file:tinycloud", "sa", "");
                    Statement s = c.createStatement();
                    ResultSet rs = s.executeQuery("SELECT * FROM directories");
                    rs = s.executeQuery("SELECT * FROM options WHERE name = 'server'");
                    rs.next();
                    server = rs.getString("value");
                    rs = s.executeQuery("SELECT * FROM options WHERE name = 'port'");
                    rs.next();
                    port = rs.getString("value");
                    s.executeQuery("SHUTDOWN");
                    s.close();
                    c.close();
                } catch (Exception ex) {
                    System.out.print(ex);
                }
                Client client = new Client(server + ":" + port, "80");
                int i = 0;
                int j = l.size();
                mainFrame.setProgressBar(i, j);
                for(String f : l) {
                    if(!client.upload(getPath(f), f)) {
                        mainFrame.setError("Impossible d'uploader");
                        break;
                    }
                    i++;
                    mainFrame.setProgressBar(i, j);
                }
                mainFrame.setEnd();
                update();
            }
            try {
                Thread.sleep(60000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }


    private boolean check() {
        Connection c;
        boolean m = false;
        try {
            Class.forName("org.hsqldb.jdbcDriver").newInstance();
            c = DriverManager.getConnection("jdbc:hsqldb:file:tinycloud", "sa", "");
            Statement s = c.createStatement();
            ResultSet rs = s.executeQuery("SELECT * FROM directories");
            File f;
            while(rs.next()) {
                f = new File(rs.getString("filename"));
                if(f.lastModified() != rs.getLong("d"))
                {
                    m = true;
                    break;
                }
            }
            s.executeQuery("SHUTDOWN");
            s.close();
            c.close();
        } catch (Exception ex) {
            System.out.print(ex);
        }
        return m;
    }

    private LinkedList<String> getList()
    {
        LinkedList<String> l = new LinkedList<String>();
        Connection c;
        try {
            Class.forName("org.hsqldb.jdbcDriver").newInstance();
            c = DriverManager.getConnection("jdbc:hsqldb:file:tinycloud", "sa", "");
            Statement s = c.createStatement();
            ResultSet rs = s.executeQuery("SELECT * FROM directories");
            while(rs.next()) {
                mkList(l, rs.getString("filename"), rs.getLong("d"));
            }
            s.executeQuery("SHUTDOWN");
            s.close();
            c.close();
        } catch (Exception ex) {
            System.out.print(ex);
        }
        return l;
    }

    private void mkList(LinkedList<String> l, String path, long d) {
        File f = new File(path);
        if(f.lastModified() > d) {
            if(f.isDirectory()) {
                String[] f2 = f.list();
                for (String s : f2) {
                    mkList(l, path + "/" + s, d);

                }
            } else {
                l.add(path);
            }
        }
    }

    private void update() {
        Connection c;
        File f;
        try {
            Class.forName("org.hsqldb.jdbcDriver").newInstance();
            c = DriverManager.getConnection("jdbc:hsqldb:file:tinycloud", "sa", "");
            Statement s = c.createStatement();
            ResultSet rs = s.executeQuery("SELECT * FROM directories");
            while(rs.next()) {
                f = new File(rs.getString("filename"));
                if(f.lastModified() > rs.getLong("d")) {
                    s.executeUpdate("UPDATE directories SET d = "+f.lastModified()+" WHERE filename = '"+rs.getString("filename")+"'");
                }
            }
            s.executeQuery("SHUTDOWN");
            s.close();
            c.close();
        } catch (Exception ex) {
            System.out.print(ex);
        }
    }

    private String getPath(String filename) {
        Connection c;
        File f;
        StringTokenizer s1;
        StringTokenizer s2;
        String s1t;
        String s2t;
        String b = null;
        boolean end = true;
        try {
            Class.forName("org.hsqldb.jdbcDriver").newInstance();
            c = DriverManager.getConnection("jdbc:hsqldb:file:tinycloud", "sa", "");
            Statement s = c.createStatement();
            ResultSet rs = s.executeQuery("SELECT * FROM directories");
            while(rs.next()) {
                s1 = new StringTokenizer(filename, "/");
                s2 = new StringTokenizer(rs.getString("filename"), "/");
                b = new String();
                end = true;
                while(s1.hasMoreElements() && end) {
                    s1t = s1.nextToken();
                    if(s2.hasMoreTokens()){
                    s2t = s2.nextToken();
                    } else {
                        s2t=null;
                    }
                    if(s2t != null) {
                    if (s1t.equals(s2t)) {
                        if(!s2.hasMoreTokens()){
                            b += "/" + s2t;
                        }
                    } else {
                        end  = false;
                    }
                    } else {
                        if(s1.hasMoreElements()) {
                            b += "/" + s1t;
                        } else {
                            return b;
                        }
                    }
                }
            }
            s.executeQuery("SHUTDOWN");
            s.close();
            c.close();
        } catch (Exception ex) {
            System.out.print(ex);
        }
        return "";
    }
}
